<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <canvas
      id="canvas"
      width="500"
      height="500"
      style="border: 1px red solid"
    ></canvas>
    <button type="button" id="btn">按钮</button>
  </body>
</html>
<script>
  async function main() {
    const cnavas = document.getElementById("canvas");
    const cxt = canvas.getContext("2d");
    cxt.font = "bold 30px 宋体";
    // cxt.strokeStyle = "red";
    // cxt.strokeText("hello", 30, 60);
    cxt.fillStyle = "red";
    const text = "hello world 你好 世界 世界杯";
    cxt.fillText(text, 40, 80);

    cxt.fillText(text, 40, 40, 200);

    // 获取文本的宽度
    const measureText = cxt.measureText(text);

    console.log(measureText); // 这个属性对于实现水平居中是有好处的

    cxt.moveTo(200, 100);
    cxt.lineTo(200, 220);
    cxt.strokeStyle = "red";
    cxt.stroke();

    cxt.textAlign = "center";

    cxt.fillText(text, 200, 120, 200);

    cxt.textAlign = "left";

    cxt.fillText(text, 200, 160, 200);

    cxt.textAlign = "right";

    cxt.fillText(text, 200, 200, 200);

    // 处理变形

    cxt.fillStyle = "red";
    // cxt.translate(10, 10);
    cxt.rect(100, 300, 340, 180);
    cxt.fill();

    function clearRect() {
      //   cxt.clearRect(0, 0, canvas.width, canvas.height);
      cxt.clearRect(0, 0, 500, 500);  // 平移也会影响到清除的效果的
    }

    document.getElementById("btn").onclick = () => {
      clearRect();
      cxt.translate(-20, -20);
      cxt.rect(100, 300, 340, 180);
      cxt.fill();
    };
    // 处理渐变
  }

  main();
</script>
